package com.itheima.tomcat;

import com.itheima.pojo.Invocation;
import com.itheima.pojo.URL;
import com.itheima.registry.NativeRegistry;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;

/**
 * @author 薛虎
 * @date 2021/1/22 9:38
 */
public class HttpServerHandler {

    /**
     * 服务的处理
     */
    public void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            //服务器请求的处理逻辑

            //1.通过请求流获取请求服务调用的参数
            InputStream inputStream = req.getInputStream();

            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);


            Invocation invocation = (Invocation) objectInputStream.readObject();
            //2.从注册中心获取服务的列表
            Class impClass = NativeRegistry.get(new URL("localhost", 8080), invocation.getInterfacerName());

            //3.调用服务 反射
            Method method = impClass.getMethod(invocation.getMethodName(), invocation.getParamTypes());

            String result = (String) method.invoke(impClass.newInstance(), invocation.getParams());

            //4.结果返回
            IOUtils.write(result, resp.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
